//
//  LBDatabase.m
//  LBReactPatcher
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay All rights reserved.
//

#import "LBDatabase.h"

@interface LBDatabase()

@property (nonatomic, strong, readwrite) FMDatabaseQueue *queue;

@end

@implementation LBDatabase

+ (instancetype)database:(NSString *)sqlName {
    NSString *sqlPath = [[self rootPath] stringByAppendingPathComponent:sqlName];
    if (sqlName.length > 0) {
        
        BOOL isExist = YES;
        if (isExist) {
            LBDatabase *db = [self databaseWithPath:sqlPath];
            if (![db open]) {
                db = nil;
            } else {
                db.queue = [FMDatabaseQueue databaseQueueWithPath:sqlPath];
                [db inspectTables];
            }
            return db;
        }
    }
    return nil;
}

+ (NSString *)rootPath {
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *sqlPath = [docPath stringByAppendingPathComponent:@"sql"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    BOOL isExist = [manager fileExistsAtPath:sqlPath isDirectory:NULL];
    
    if (!isExist) {
        isExist = [manager createDirectoryAtPath:sqlPath
                     withIntermediateDirectories:YES
                                      attributes:nil
                                           error:NULL];
    }
    
    if (isExist) {
        return sqlPath;
    }
    
    return nil;
}

//业务处理
- (void)inspectTables {
    [self createPatcher];
}

//列表消息
- (void)createPatcher {
    NSString *tableName = @"patcher";
    NSString *sql = [NSString stringWithFormat:@"create table %@ ( \
                     id integer primary key, \
                     type int, \
                     app_type int , \
                     bundle_type int , \
                     app_identifier varchar(50) , \
                     app_version varchar(50) , \
                     main_version int , \
                     module_name varchar(50) , \
                     check_code varchar(50) , \
                     is_main int , \
                     state int , \
                     url text , \
                     data_flag int not null default 1 , \
                     create_time timestamp not null default current_timestamp )", tableName];
    [self createTable:tableName
                  sql:sql];
}

- (BOOL)createTable:(NSString *)tableName
                sql:(NSString *)sql {
    __block BOOL isSuccess = NO;
    if(![self isExistTable:tableName]){
        [self.queue inTransaction:^(FMDatabase * _Nonnull db, BOOL * _Nonnull rollback) {
            isSuccess = [db executeUpdate:sql];
            if (!isSuccess) {
                *rollback = YES;
            }
        }];
    }
    return isSuccess;
}

//判断表是否存在
- (BOOL)isExistTable:(NSString *)tableName {
    if (tableName.length == 0) {
        return NO;
    }
    __block BOOL isExist = NO;
    NSString *sql = [NSString stringWithFormat:@"select count(*) from sqlite_master where type ='table' and name = '%@'",tableName];
    [self.queue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:sql];
        if([resultSet next]) {
            NSInteger count = [resultSet intForColumnIndex:0];
            isExist = count > 0;
        }
        [resultSet close];
    }];
    
    return isExist;
}

- (BOOL)close {
    return [super close];
}

@end
